<!DOCTYPE html>
<html>
	<head>
		<title>优惠券添加/编辑</title>
		<meta charset="utf-8">
		<meta name="viewport"
			content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<!-- 所有的 css & js 资源 -->
		<link rel="stylesheet" href="https://unpkg.com/element-ui@2.13.0/lib/theme-chalk/index.css">
		<link rel="stylesheet" href="../../static/sa.css">
		<script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script>
		<script src="https://unpkg.com/element-ui@2.13.0/lib/index.js"></script>
		<script src="https://unpkg.com/http-vue-loader@1.4.2/src/httpVueLoader.js"></script>
		<script src="https://unpkg.com/jquery@3.4.1/dist/jquery.min.js"></script>
		<script src="https://www.layuicdn.com/layer-v3.1.1/layer.js"></script>
		<script src="../../static/sa.js"></script>
	</head>
	<body>
		<div class="vue-box" style="display: none;" :style="'display: block;'">
			<div class="c-panel">
				<div class="c-title">优惠券{{ isAdd ? '添加' : '编辑' }}</div>
				<el-form v-if="m" label-width="120px" :rules="rules" ref="form" :model="m">
					
					<div class="c-item br">
						<label class="c-label">优惠金额：</label>
						<el-input-number v-model="m.amount" :precision="2" :step="1" :min="0" :max="99999"
							controls-position="right" placeholder="请输入优惠金额" style="width: 200px;">
						</el-input-number>
						<span class="tips">
							<i class="el-icon-coin" style="margin-right: 4px;"></i>
							元
						</span>
					</div>
					<div class="c-item br">
						<label class="c-label">最低消费：</label>
						<el-input-number v-model="m.minOrderAmount" :precision="2" :step="10" :min="0" :max="99999"
							controls-position="right" placeholder="请输入最低消费金额" style="width: 200px;">
						</el-input-number>
						<span class="tips">
							<i class="el-icon-shopping-cart-2" style="margin-right: 4px;"></i>
							元（0表示无门槛）
						</span>
					</div>
					<div class="c-item br">
						<label class="c-label">优惠券名称：</label>
						<el-input v-model="m.name" placeholder="请输入优惠券名称" maxlength="50" show-word-limit
							style="width: 400px;">
							<template slot="prepend">
								<i class="el-icon-price-tag"></i>
							</template>
							<template slot="append">
								<el-button @click="generateName" size="mini" type="primary" icon="el-icon-magic-stick">
									自动生成
								</el-button>
							</template>
						</el-input>
						<span class="tips">
							<i class="el-icon-info" style="margin-right: 4px;"></i>
							根据优惠金额和最低消费自动生成名称，或手动输入
						</span>
					</div>
					<div class="c-item br">
						<label class="c-label">优惠券状态：</label>
						<el-select v-model="m.status" placeholder="请选择优惠券状态" style="width: 200px;">
							<el-option label="商品券" value="shopping">
								<span style="color: #ff6b6b;">
									<i class="el-icon-goods"></i> 商品券
								</span>
							</el-option>
							<el-option label="新人券" value="newcomer">
								<span style="color: #ff6b6b;">
									<i class="el-icon-user"></i> 新人券
								</span>
							</el-option>
							<el-option label="活动券" value="activity">
								<span style="color: #ff6b6b;">
									<i class="el-icon-star-on"></i> 活动券
								</span>
							</el-option>
						</el-select>
						<span class="tips">
							<i class="el-icon-info" style="margin-right: 4px;"></i>
							选择优惠券的类型和用途
						</span>
					</div>
					<div class="c-item br">
						<label class="c-label">有效期：</label>
						<el-date-picker v-model="dateRange" type="daterange" range-separator="至"
							start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd"
							:picker-options="pickerOptions" @change="handleDateChange" style="width: 300px;">
						</el-date-picker>
						<span class="tips">
							<i class="el-icon-date" style="margin-right: 4px;"></i>
							设置优惠券的使用有效期（默认一个月有效期）
						</span>
					</div>
					<div class="c-item br" style="justify-content: center; margin-top: 30px; padding-top: 20px; border-top: 1px solid #ebeef5;">
						<el-button type="primary" icon="el-icon-check" @click="ok" size="medium"
							:loading="loading" style="min-width: 120px;">
							{{ isAdd ? '确认添加' : '确认修改' }}
						</el-button>
						<el-button @click="sa.closeCurrIframe()" icon="el-icon-close" size="medium"
							style="min-width: 100px;">
							取消
						</el-button>
					</div>
				</el-form>
			</div>
		</div>
		<script>
			new Vue({
				el: '.vue-box',
				data: {
					isAdd: true,
					loading: false,
					dateRange: [],
					showCouponDialog: false, // 控制优惠券列表对话框显示
					existingCoupons: [], // 现有优惠券列表
					couponLoading: false, // 加载现有优惠券的loading状态
					pickerOptions: {
						disabledDate(time) {
							return time.getTime() < Date.now() - 8.64e7; // 禁用今天之前的日期
						}
					},
					m: {
						id: '',
						name: '',
						amount: 0,
						startDate: '',
						endDate: '',
						minOrderAmount: 0,
						status: 'shopping' // 默认为商品券
					},
					rules: {
						name: [{
								required: true,
								message: '请输入优惠券名称',
								trigger: 'blur'
							},
							{
								min: 2,
								max: 50,
								message: '长度在 2 到 50 个字符',
								trigger: 'blur'
							}
						],
						amount: [{
								required: true,
								message: '请输入优惠金额',
								trigger: 'blur'
							},
							{
								type: 'number',
								min: 0,
								message: '金额必须大于0',
								trigger: 'blur'
							}
						],
						minOrderAmount: [{
							type: 'number',
							min: 0,
							message: '最低消费不能小于0',
							trigger: 'blur'
						}],
						status: [{
							required: true,
							message: '请选择优惠券状态',
							trigger: 'change'
						}]
					}
				},
				created() {
					// 获取编辑id和数据
					var id = sa.p('id');
					var couponData = sa.p('couponData');
					this.isAdd = (id == null || id == '' || id == '-1');
					if (!this.isAdd && couponData) {
						this.m = couponData;
						// 设置日期范围
						this.dateRange = [this.m.startDate, this.m.endDate];
					} else if (this.isAdd) {
						// 新增模式下设置默认一个月有效期
						this.setDefaultDateRange();
					}
				},
				methods: {
					// 设置默认日期范围（一个月有效期）
					setDefaultDateRange: function() {
						const today = new Date();
						const oneMonthLater = new Date();
						oneMonthLater.setMonth(today.getMonth() + 1);

						// 格式化日期为 yyyy-MM-dd
						const formatDate = function(date) {
							const year = date.getFullYear();
							const month = String(date.getMonth() + 1).padStart(2, '0');
							const day = String(date.getDate()).padStart(2, '0');
							return `${year}-${month}-${day}`;
						};

						this.m.startDate = formatDate(today);
						this.m.endDate = formatDate(oneMonthLater);
						this.dateRange = [this.m.startDate, this.m.endDate];
					},
					// 日期改变时
					handleDateChange: function(val) {
						if (val) {
							this.m.startDate = val[0];
							this.m.endDate = val[1];
						} else {
							this.m.startDate = '';
							this.m.endDate = '';
						}
					},
					// 自动生成优惠券名称
					generateName: function() {
						if (!this.m.amount || this.m.amount <= 0) {
							this.$message.warning('请先输入优惠金额');
							return;
						}

						// 获取状态文本
						const statusMap = {
							'shopping': '商品券',
							'newcomer': '新人券',
							'activity': '活动券'
						};
						const statusText = statusMap[this.m.status] || '优惠券';

						// 根据最低消费金额生成名称
						let name = '';
						if (this.m.minOrderAmount && this.m.minOrderAmount > 0) {
							// 有门槛的情况：满XX减XX券
							name = `满${this.m.minOrderAmount}减${this.m.amount}${statusText}`;
						} else {
							// 无门槛的情况：XX元无门槛券
							name = `${this.m.amount}元无门槛${statusText}`;
						}

						this.m.name = name;
						this.$message.success('名称生成成功');
					},
					// 判断名称是否为自动生成的格式
					isAutoGeneratedName: function() {
						if (!this.m.name) return false;
						// 检查是否包含自动生成的关键词
						const autoPatterns = [
							/满\d+减\d+/,  // 满XX减XX
							/\d+元无门槛/
						];
						return autoPatterns.some(pattern => pattern.test(this.m.name));
					},
					// 提交数据
					ok: function() {
						this.$refs.form.validate((valid) => {
							if (!valid) return;
							if (!this.m.startDate || !this.m.endDate) {
								return this.$message.error('请选择有效期');
							}

							this.loading = true;

							// 数据预处理和验证
							const submitData = {
								name: this.m.name.trim(), // 去除可能的空格
								amount: parseFloat(this.m.amount), // 转换为数字
								start_date: this.m.startDate, // 匹配数据库列名
								end_date: this.m.endDate, // 匹配数据库列名
								min_order_amount: parseFloat(this.m.minOrderAmount), // 匹配数据库列名
								status: this.m.status // 优惠券状态
							};

							// 详细的调试日志
							console.log('提交的数据结构:', {
								数据库表结构: {
									name: 'VARCHAR(50)',
									amount: 'DECIMAL(10,2)',
									start_date: 'DATE',
									end_date: 'DATE',
									min_order_amount: 'DECIMAL(10,2)'
								},
								发送的数据: submitData,
								数据类型: {
									name: typeof submitData.name,
									amount: typeof submitData.amount,
									start_date: typeof submitData.start_date,
									end_date: typeof submitData.end_date,
									min_order_amount: typeof submitData.min_order_amount
								},
								原始表单数据: this.m
							});

							// 验证所有必填字段
							if (!submitData.name) {
								return this.$message.error('请输入优惠券名称');
							}

							if (isNaN(submitData.amount) || submitData.amount <= 0) {
								return this.$message.error('请输入正确的优惠金额');
							}

							if (!submitData.start_date || !submitData.end_date) {
								return this.$message.error('请选择有效期');
							}

							if (submitData.end_date < submitData.start_date) {
								return this.$message.error('结束日期不能早于开始日期');
							}

							if (isNaN(submitData.min_order_amount) || submitData.min_order_amount < 0) {
								return this.$message.error('请输入正确的最低消费金额');
							}

							// 最终发送的数据
							console.log('Final data to be sent:', JSON.stringify(submitData, null, 2));

							$.ajax({
								url: 'http://localhost:8080/coupon/addCoupon',
								type: 'POST',
								contentType: 'application/json;charset=UTF-8',
								data: JSON.stringify(submitData),
								success: function(res) {
									if (res.code === 200) {
										this.$message.success('添加成功');
										// 重置表单
										this.resetForm();
										// 刷新父页面的列表
										if (window.parent && window.parent.app) {
											window.parent.app.f5();
										}
									} else {
										this.$message.error(res.message || '添加失败');
									}
								}.bind(this)
							});
						});
					},
					// 重置表单
					resetForm() {
						this.m = {
							id: '',
							name: '',
							amount: 0,
							startDate: '',
							endDate: '',
							minOrderAmount: 0,
							status: 'shopping' // 重置为默认状态
						};
						this.dateRange = [];
						this.$refs.form.resetFields();
						// 重置后设置默认一个月有效期
						this.setDefaultDateRange();
					}
				},
				// 监听器 - 当金额或状态变化时提示用户可以重新生成名称
				watch: {
					'm.amount': function(newVal, oldVal) {
						if (newVal && newVal !== oldVal && this.m.name) {
							// 如果名称看起来是自动生成的，则自动更新
							if (this.isAutoGeneratedName()) {
								this.generateName();
							}
						}
					},
					'm.minOrderAmount': function(newVal, oldVal) {
						if (newVal !== oldVal && this.m.name) {
							// 如果名称看起来是自动生成的，则自动更新
							if (this.isAutoGeneratedName()) {
								this.generateName();
							}
						}
					},
					'm.status': function(newVal, oldVal) {
						if (newVal !== oldVal && this.m.name) {
							// 如果名称看起来是自动生成的，则自动更新
							if (this.isAutoGeneratedName()) {
								this.generateName();
							}
						}
					}
				}
			})
		</script>
		<style>
			.c-item {
				display: flex;
				align-items: center;
				margin-bottom: 20px;
				padding: 0 15px;
				flex-wrap: wrap;
			}

			.c-label {
				width: 120px;
				text-align: right;
				padding-right: 12px;
				line-height: 40px;
				flex-shrink: 0;
				font-weight: 500;
				color: #606266;
			}

			.tips {
				color: #909399;
				font-size: 12px;
				margin-left: 10px;
				line-height: 1.4;
				flex-basis: 100%;
				margin-top: 5px;
				padding-left: 132px;
			}

			/* 输入框样式优化 */
			.el-input {
				transition: all 0.3s;
			}

			.el-input__inner {
				border-radius: 6px;
				border: 1px solid #dcdfe6;
				transition: all 0.3s;
				font-size: 14px;
				height: 40px;
				line-height: 40px;
			}

			.el-input__inner:focus {
				border-color: #409eff;
				box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
			}

			.el-input__inner:hover {
				border-color: #c0c4cc;
			}

			/* 输入框前缀图标样式 */
			.el-input-group__prepend {
				background-color: #f5f7fa;
				border-color: #dcdfe6;
				color: #909399;
				border-radius: 6px 0 0 6px;
			}

			.el-input-number {
				transition: all 0.3s;
			}

			.el-input-number .el-input__inner {
				text-align: left;
				height: 40px;
				line-height: 40px;
			}

			.el-input-number__increase,
			.el-input-number__decrease {
				border-radius: 0 6px 6px 0;
			}

			.el-date-editor {
				transition: all 0.3s;
			}

			.el-date-editor .el-input__inner {
				border-radius: 6px;
				height: 40px;
				line-height: 40px;
			}

			.el-date-editor:hover .el-input__inner {
				border-color: #c0c4cc;
			}

			.el-date-editor.is-active .el-input__inner {
				border-color: #409eff;
				box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
			}



			/* 响应式设计 */
			@media (max-width: 768px) {
				.c-item {
					flex-direction: column;
					align-items: flex-start;
				}

				.c-label {
					width: 100%;
					text-align: left;
					padding-right: 0;
					margin-bottom: 8px;
				}

				.tips {
					padding-left: 0;
					margin-top: 8px;
				}

				/* 移动端输入框宽度调整 */
				.el-input {
					width: 100% !important;
					max-width: 400px;
				}

				.el-input-number {
					width: 100% !important;
					max-width: 200px;
				}

				.el-date-picker {
					width: 100% !important;
					max-width: 300px;
				}
			}

			/* 表单容器优化 */
			.c-panel {
				background: #fff;
				border-radius: 8px;
				box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
				padding: 24px;
				margin: 20px;
			}

			.c-title {
				font-size: 18px;
				font-weight: 600;
				color: #303133;
				margin-bottom: 24px;
				padding-bottom: 12px;
				border-bottom: 2px solid #409eff;
			}

			/* 按钮样式优化 */
			.el-button {
				border-radius: 6px;
				padding: 12px 24px;
				font-weight: 500;
			}

			.el-button + .el-button {
				margin-left: 12px;
			}
		</style>
	</body>
</html>